package main

import (
	"task/config"
	"task/driver"
	service "task/service/executor"

	"github.com/apache/pulsar-client-go/pulsar"
	log "github.com/sirupsen/logrus"
)

func main() {
	var (
		consumer pulsar.Consumer
		err      error
	)
	// 日志初始化
	log.SetFormatter(&log.TextFormatter{
		TimestampFormat: "2006-01-02 15:04:05.000",
	})
	// 初始化数据库
	driver.InitEngine()
	// 初始化执行处理器
	service.InitExecutorHandler()
	// 缓存并定时更新处理单元
	service.SetProcessorMap()
	go service.SyncProcessorMap()
	// 初始化business grpc客户端
	conn := driver.InitBusinessClient()
	defer conn.Close()
	// 初始化消息队列组件
	driver.InitPulsarClient()
	defer driver.PulsarClient.Close()
	// 初始化调度消息生产者
	driver.InitDispatchProducer()
	defer driver.DispatchProducer.Close()
	// 初始化业务消息生产者
	driver.InitBusiness1Producer()
	defer driver.Business1Producer.Close()
	driver.InitBusiness2Producer()
	defer driver.Business2Producer.Close()
	// 开启metrics服务
	go driver.StartMetricsServer()
	// 创建执行消息消费者
	options := pulsar.ConsumerOptions{
		Topic:            config.Conf.Pulsar.ExecuteTopic,
		SubscriptionName: config.Conf.Pulsar.SubscriptionName,
		Type:             pulsar.Shared,
	}
	options.MessageChannel = service.ExecuteEventCh
	if consumer, err = driver.PulsarClient.Subscribe(options); err != nil {
		log.Panic("Failed not create pulsar consumer:", err)
	}
	defer consumer.Close()
	// 监听执行事件
	service.ListenExecuteEvent(consumer)
	select {}
}
